﻿using System;
using System.Collections.Generic;
using Rhino.Mocks;
using NUnit.Framework;
using System.Threading;
using System.Web;
using System.Web.Caching;

namespace mForum.Web.Common.Tests.Infrastructure.CacheTests
{
    using mForum.Web.Common.Infrastructure.Cache;

    [TestFixture]
    public class CacheTests
    {
        private ICache _cache;

        [SetUp]
        public void Setup()
        {
            _cache = new Cache(HttpRuntime.Cache);
        }

        [Test]
        public void can_cache_item()
        {
            string key = "test";
            string excpectedValue = "Testing cache";

            _cache.Set<string>(key, excpectedValue, DateTime.Now.AddDays(1));

            string result = _cache.Get<string>(key);

            Assert.AreEqual(excpectedValue, result);
        }

        [Test]
        public void can_repleace_existing_cache_item()
        {
            string key = "test";
            string baseValue = "Test";
            string excpectedValue = "Testing cache";

            _cache.Set<string>(key, baseValue, DateTime.Now.AddSeconds(15));
            _cache.Set<string>(key, excpectedValue, DateTime.Now.AddSeconds(20));

            string result = _cache.Get<string>(key);

            Assert.AreEqual(excpectedValue, result);
        }

        [Test]
        public void can_remove_cached_item()
        {
            string key = "test";
            string excpectedValue = "Testing cache";

            _cache.Set<string>(key, excpectedValue, DateTime.Now.AddDays(1));
            _cache.Remove<string>(key);

            Assert.IsNull(_cache.Get<string>(key));
        }

        [Test]
        public void can_clear_whole_cache()
        {
            string key = "test";
            string key1 = "test1";
            string key2 = "test2";
            string excpectedValue = "Testing cache";

            _cache.Set<string>(key, excpectedValue, DateTime.Now.AddDays(1));
            _cache.Set<string>(key1, excpectedValue, DateTime.Now.AddDays(1));
            _cache.Set<string>(key2, excpectedValue, DateTime.Now.AddDays(1));

            _cache.Clear();

            Assert.IsNull(_cache.Get<string>(key));
            Assert.IsNull(_cache.Get<string>(key1));
            Assert.IsNull(_cache.Get<string>(key2));
        }

        [Test]
        public void can_check_if_cache_expire_properly()
        {
            string key = "test";
            string excpectedValue = "Testing cache";
            TimeSpan timeInterval = new TimeSpan(0,0,2);
            TimeSpan waitTime = new TimeSpan(0,0,3);

            _cache.Set<string>(key, excpectedValue, timeInterval);

            Thread.Sleep(waitTime);

            Assert.IsNull(_cache.Get<string>(key));
        }
    }
}
